package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private SeckillVoucherMapper seckillVoucherMapper;

    private IVoucherOrderService proxy;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    private static final ExecutorService SECKILL_EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();

    private static final BlockingQueue<VoucherOrder> ORDER_TASK_QUEUE = new ArrayBlockingQueue(1024 * 1024);

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    @PostConstruct
    private void init() {
        SECKILL_EXECUTOR_SERVICE.submit(() -> {
            while (true) {
                try {
                    VoucherOrder voucherOrder = ORDER_TASK_QUEUE.take();
                    proxy.createVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT, Collections.emptyList(), voucherId.toString(), userId.toString());
        if (result.longValue() != 0) {
            return Result.fail(result.longValue() == 1 ? "库存不足" : "不能重复下单");
        }
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        long orderId = redisIdWorker.nextId("order");
        VoucherOrder order = new VoucherOrder();
        order.setVoucherId(voucherId);
        order.setUserId(userId);
        order.setId(orderId);
        try {
            ORDER_TASK_QUEUE.put(order);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.ok(orderId);
    }

    @Override
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        seckillVoucherService.update().setSql("stock = stock - 1").eq("voucher_id", voucherOrder.getVoucherId()).update();
        save(voucherOrder);
    }

//    @Override
//    @Transactional
//    public Result seckillVoucher(Long voucherId) {
////        // 1. 查询优惠券
////        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
////        // 2. 判断秒杀是否开始
////        LocalDateTime now = LocalDateTime.now();
////        if (voucher.getBeginTime().isAfter(now)) {
////            return Result.fail("秒杀未开始");
////        }
////        // 3. 判断秒杀是否结束
////        if (voucher.getEndTime().isBefore(now)) {
////            return Result.fail("秒杀已结束");
////        }
////        // 4. 判断库存是否充足
////        if (voucher.getStock() < 1) {
////            return Result.fail("库存不足");
////        }
////        // 5. 扣减库存
////        boolean success = seckillVoucherService.update().setSql("stock = stock - 1")
////                        .eq( "voucher_id", voucherId).eq("stock", ).update();
////        if (!success) {
////            return Result.fail("库存不足");
////        }
////        // 6. 创建订单
////        VoucherOrder voucherOrder = new VoucherOrder();
////        long orderId = redisIdWorker.nextId("order");
////        voucherOrder.setId(orderId);
////        voucherOrder.setUserId(voucherOrder.getUserId());
////        voucherOrder.setVoucherId(voucherId);
//
//        // 1. 查询优惠券
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//        // 2. 判断秒杀是否开始
//        LocalDateTime now = LocalDateTime.now();
//        if (voucher.getBeginTime().isAfter(now)) {
//            return Result.fail("秒杀未开始");
//        }
//        // 3. 判断秒杀是否结束
//        if (voucher.getEndTime().isBefore(now)) {
//            return Result.fail("秒杀已结束");
//        }
//        // 4. 判断库存是否充足，采用乐观锁实现，而非悲观锁，所以这里判断库存数量的时候不用加锁
//        if (voucher.getStock() < 1) {
//            return Result.fail("库存不足");
//        }
//        // 5. 创建订单
//        Long userId = UserHolder.getUser().getId();
//        RLock lock = redissonClient.getLock("lock:order" + userId);
//        boolean isLock = lock.tryLock();
//        if (isLock) {
//            try {
//                IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//                return proxy.createVoucherOrder(voucherId);
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            } finally {
//                lock.unlock();
//            }
//        } else {
//            return Result.fail("一人只能购买一个优惠券");
//        }
//    }
//
//    @Override
//    @Transactional
//    public Result createVoucherOrder(Long voucherId) {
//        // 6. 扣减库存
//        boolean success = seckillVoucherService
//                .update()
//                .setSql("stock = stock - 1")
//                .eq( "voucher_id", voucherId).gt("stock", 0)
//                .update();
//        if (!success) {
//            return Result.fail("库存不足");
//        }
//        // 7. 创建订单
//        long orderId = redisIdWorker.nextId("order");
//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setId(orderId);
//        voucherOrder.setUserId(UserHolder.getUser().getId());
//        voucherOrder.setVoucherId(voucherId);
//        save(voucherOrder);
//        return Result.ok();
//    }
    // 用redis的set来存储每个优惠券已经购买的用户信息
    // 在redis中用脚本来实现判断用户是否具备购买资格、优惠券库存是否足够、优惠券是否过期等
    // 如果用户可以下单，使用异步线程完成后续的订单创建、库存扣减等操作

//    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
//    static {
//        SECKILL_SCRIPT = new DefaultRedisScript<>();
//        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
//        SECKILL_SCRIPT.setResultType(Long.class);
//    }
//
//    // 代理对象
//    private IVoucherOrderService proxy;
//
//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        // 1. 执行lua脚本
//        Long userId = UserHolder.getUser().getId();
//        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT, Collections.emptyList(), voucherId.toString(), userId.toString());
//        // 2. 判断购买资格
//        int r = result.intValue();
//        if (r != 0) {
//            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
//        }
//        // 3. 异步下单
//        long orderId = redisIdWorker.nextId("order");
//        proxy = (IVoucherOrderService) AopContext.currentProxy();
//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setId(orderId);
//        voucherOrder.setUserId(userId);
//        voucherOrder.setVoucherId(voucherId);
//        try {
//            orderTasks.put(voucherOrder);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//        return Result.ok(orderId);
//    }
//
//    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
//    private static final ExecutorService SECKILL_EXECUTOR = Executors.newSingleThreadExecutor();
//
//    @PostConstruct
//    private void init() {
//        SECKILL_EXECUTOR.submit(() -> {
//            while (true) {
//
//            }
//        });
//    }


//    private class VoucherOrderHandler implements Runnable {
//
//        @Override
//        public void run() {
//            while (true) {
//                try {
//                    VoucherOrder order = orderTasks.take();
//                } catch (Exception e) {
//                    log.error("处理订单异常", e);
//                }
//            }
//        }
//    }
//
//    private void handleOrder()

//    @Override
//    @Transactional
//    public Result createVoucherOrder(Long voucherId) {
//        // 6. 扣减库存
//        boolean success = seckillVoucherService
//                .update()
//                .setSql("stock = stock - 1")
//                .eq( "voucher_id", voucherId).gt("stock", 0)
//                .update();
//        if (!success) {
//            return Result.fail("库存不足");
//        }
//        // 7. 创建订单
//        long orderId = redisIdWorker.nextId("order");
//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setId(orderId);
//        voucherOrder.setUserId(UserHolder.getUser().getId());
//        voucherOrder.setVoucherId(voucherId);
//        save(voucherOrder);
//        return Result.ok(orderId);
//    }

}
